package com.buildings.activity.reinforce;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.buildings.R;
import com.buildings.activity.RegisterActivity;
import com.buildings.api.Api;
import com.buildings.base.BaseFormActivity;
import com.buildings.bean.BuildingCodeBean;
import com.buildings.bean.ImageURL;
import com.buildings.bean.LoginBean;
import com.buildings.bean.ReinforceImageResult;
import com.buildings.bean.ReinforceResult;
import com.buildings.http.BaseCallBack;
import com.buildings.http.JsonBuilder;
import com.buildings.http.MyHttpClient;
import com.buildings.util.CustomToast;
import com.buildings.util.DialogUtils;
import com.buildings.util.FormDataUtil;
import com.buildings.util.PickViewUtil;
import com.buildings.util.SPUtil;
import com.buildings.util.Utils;
import com.buildings.view.MyGridView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.common.Constant;
import com.yuyh.library.imgsel.common.ImageLoader;
import com.yuyh.library.imgsel.config.ISListConfig;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import org.json.JSONException;
import org.json.JSONObject;

import static com.buildings.activity.reinforce.CheckUtils.checkNullEditText;
import static com.buildings.activity.reinforce.CheckUtils.formatImageList;

/**
 * @author yiem
 * @packager com.buildings.activity
 * @date 2020/8/27
 **/
public class HouseReinforceFormActivity extends BaseFormActivity
    implements ImageAdapter.ImageAdapterListener {

  private String from;

  public static void intentHouseReinforceFormActivity(Activity context,
      ReinforceResult.ReinforceData data, String from) {
    Intent intent = new Intent();
    intent.setClass(context, HouseReinforceFormActivity.class);
    intent.putExtra("reinforce", data);
    intent.putExtra("from", from);// FROM_TASK_MAP 地图  list 列表
    context.startActivityForResult(intent, 1000);
  }

  //tool bar
  @BindView(R.id.tv_title) TextView tvTitle;
  @BindView(R.id.tv_right_text) TextView tvSave;
  @BindView(R.id.tv_left_text) TextView tvClear;
  @BindView(R.id.iv_back) ImageView ivBack;
  @BindView(R.id.tv_reason) TextView tvReason;//审核未通过原因

  //first
  @BindView(R.id.et_province) EditText etProvince;//省市区
  @BindView(R.id.et_city) EditText etCity;//省市区
  @BindView(R.id.et_area) EditText etArea;//省市区
  //second
  @BindView(R.id.et_lng) EditText etLng;//经度
  @BindView(R.id.et_lat) EditText etLat;//纬度
  //third
  @BindView(R.id.et_building_number) EditText etNumber;//工程编号
  //four
  @BindView(R.id.et_building_address) EditText etBuildingAddress;//工程地址
  //five
  @BindView(R.id.et_project_name) EditText mProjectName;//工程名称
  //six
  @BindView(R.id.et_project_category) EditText mProjectCategory;//工程类别
  //seven
  @BindView(R.id.et_project_type) EditText mProjectType;//工程类型
  @BindView(R.id.et_type_other) EditText mProjectTypeOther;//工程类型其它

  //eight
  @BindView(R.id.et_project_re_method) EditText mReinforceMethod;//工程加固措施
  @BindView(R.id.et_project_re_method_t) EditText mReinforceMethodT;//方式2
  @BindView(R.id.ll_project_re_method_t) LinearLayout mReinforceMethodTLayout;//方式2
  @BindView(R.id.et_method_other) EditText mReinforceMethodOther;//加固方式其它
  //nine
  @BindView(R.id.et_project_year) EditText mProjectYear;//工程年

  @BindView(R.id.et_project_moth) EditText mProjectMoth;//工程月

  @BindView(R.id.build_before_layout) MyGridView mBeforeGridView;//施工前

  @BindView(R.id.build_ing_layout) MyGridView mIngGridView;//施工过程中

  @BindView(R.id.build_after_layout) MyGridView mAfterGridView;//施工后

  @BindView(R.id.btn_commit) Button mCommitView;//提交按钮

  private ImageAdapter mBeforeAdapter;//施工前照片适配器

  private ImageAdapter mIngAdapter;//施工后照片适配器

  private ImageAdapter mAfterAdapter;//施工后照片适配器

  @BindView(R.id.re_parent_layout) LinearLayout mParentView;//

  @BindView(R.id.ll_des_building) LinearLayout mBuildingLayout;//应急避难场所

  @BindView(R.id.et_array) EditText mArrayText;//场所面积

  @BindView(R.id.et1_array) EditText mPeopleText;//可容纳人数

  @BindView(R.id.et1_project_category) EditText mLifeEditText;//是否配备生活设施

  @BindView(R.id.et2_project_category) EditText mOrEditText;//原厂地址用途

  private boolean isPictureEdit = false;
  //data
  private String lng;
  private String lat;

  private AtomicInteger imageIndex = new AtomicInteger();

  private ReinforceResult.ReinforceData reinforceData;

  private String projectCode;

  @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_reinforce_layout);
    ButterKnife.bind(this);
    initView();
    initData();
  }

  private void clear() {
    etBuildingAddress.setText("");
    mProjectName.setText("");
    mProjectCategory.setText("");
    mProjectType.setText("");
    mReinforceMethod.setText("");
    mProjectYear.setText("");
    mProjectMoth.setText("");
    mBeforeAdapter.setUrlList(new ArrayList<ImageURL>());
    mAfterAdapter.setUrlList(new ArrayList<ImageURL>());
    mIngAdapter.setUrlList(new ArrayList<ImageURL>());
  }

  @OnClick({
      R.id.tv_right_text, R.id.tv_left_text, R.id.et_province, R.id.et_area, R.id.et_city,
      R.id.et_project_category, R.id.et_project_type, R.id.et_project_re_method,
      R.id.et_project_year, R.id.et_project_moth, R.id.et_project_re_method_t, R.id.btn_commit,
      R.id.iv_back, R.id.et1_project_category, R.id.et2_project_category
  }) public void onClick(View v) {
    Utils.hintKb(activity);
    switch (v.getId()) {

      case R.id.iv_back:
        finish();
        break;
      case R.id.tv_right_text://保存
        save(0);
        break;
      case R.id.tv_left_text://清空
        clear();
        break;
      case R.id.btn_commit://提交
        if (!checkComplete()) {
          return;
        }

        save(1);
        break;

      case R.id.et_province:
        //省市区
        getDivisions("root", RegisterActivity.PROVINCE, "", null);
        break;
      case R.id.et_city:
        //省市区
        if (provinceBean == null) {
          CustomToast.showToast(activity, "请先选择省");
          return;
        }
        getDivisions(provinceBean.getDivisionId(), RegisterActivity.CITY,
            provinceBean.getDivisionType(), provinceBean);
        break;
      case R.id.et_area:
        if (cityBean == null) {
          CustomToast.showToast(activity, "请先选择市");
          return;
        }
        //省市区
        getDivisions(cityBean.getDivisionId(), RegisterActivity.AREA, "", null);
        break;
      case R.id.et_project_category://工程类别
        final List<String> category = FormDataUtil.projectCategory();
        PickViewUtil.showPickerViewOne(activity, "", category,
            new OptionsPickerView.OnOptionsSelectListener() {
              @Override
              public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String type = category.get(options1);
                final String projectType = mProjectCategory.getText().toString();
                if (TextUtils.equals(projectType, type))return;

                mProjectCategory.setText(type);
                if ("应急避难场所建设".equals(type)) {
                  mBuildingLayout.setVisibility(View.VISIBLE);
                  mProjectTypeOther.setVisibility(View.GONE);
                  mProjectType.setText("室内");
                  mLifeEditText.setText("是");
                  mOrEditText.setText("公园");
                } else if (TextUtils.equals("重要交通生命线", type)) {
                  mProjectType.setText("桥梁");
                  mBuildingLayout.setVisibility(View.GONE);
                  mProjectTypeOther.setVisibility(View.GONE);
                } else if (TextUtils.equals("电力网络", type)) {
                  mProjectType.setText("电力网络设施");
                  mBuildingLayout.setVisibility(View.GONE);
                  mProjectTypeOther.setVisibility(View.GONE);
                } else if (TextUtils.equals("电信网络", type)) {
                  mProjectType.setText("电信网络设施");
                  mBuildingLayout.setVisibility(View.GONE);
                  mProjectTypeOther.setVisibility(View.GONE);
                } else if (TextUtils.equals("水库大坝", type)) {
                  mProjectType.setText("土石坝");
                  mBuildingLayout.setVisibility(View.GONE);
                  mProjectTypeOther.setVisibility(View.GONE);
                } else if (TextUtils.equals("危险化学品厂库", type)) {
                  mProjectType.setText("设备装置");
                  mBuildingLayout.setVisibility(View.GONE);
                  mProjectTypeOther.setVisibility(View.GONE);
                } else {
                  mProjectType.setText("砖混结构");
                  mBuildingLayout.setVisibility(View.GONE);
                }
              }
            });
        break;
      case R.id.et_project_type:

        final String projectType = mProjectCategory.getText().toString();
        final List<String> types = new ArrayList<>();
        if (TextUtils.equals("应急避难场所建设", mProjectCategory.getText().toString())) {
          List<String> s = FormDataUtil.projectTypeHome();
          types.addAll(s);
        } else if (TextUtils.equals("重要交通生命线", mProjectCategory.getText().toString())) {
          List<String> s = FormDataUtil.projectLifeReinforce();
          types.addAll(s);
        } else if (TextUtils.equals("电力网络", projectType)) {
          List<String> s = FormDataUtil.powerReinforce();
          types.addAll(s);
        } else if (TextUtils.equals("电信网络", projectType)) {
          List<String> s = FormDataUtil.powerReinforce2();
          types.addAll(s);
        } else if (TextUtils.equals("水库大坝", projectType)) {
          List<String> s = FormDataUtil.waterReinforce();
          types.addAll(s);
        } else if (TextUtils.equals("危险化学品厂库", projectType)) {
          List<String> s = FormDataUtil.dangerReinforce();
          types.addAll(s);
        } else {
          List<String> s = FormDataUtil.projectType();
          types.addAll(s);
        }

        PickViewUtil.showPickerViewOne(activity, "", types,
            new OptionsPickerView.OnOptionsSelectListener() {
              @Override
              public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String type = types.get(options1);
                mProjectType.setText(type);
                mProjectTypeOther.setVisibility(
                    TextUtils.equals("其它", type) ? View.VISIBLE : View.GONE);
                mProjectTypeOther.setText("");
              }
            });
        break;
      case R.id.et_project_re_method:
        final List<String> method = FormDataUtil.getProjectMethod();
        PickViewUtil.showPickerViewOne(activity, "", method,
            new OptionsPickerView.OnOptionsSelectListener() {
              @Override
              public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String type = method.get(options1);
                mReinforceMethod.setText(type);
                if (TextUtils.equals("拆除重建", type)) {
                  mReinforceMethodTLayout.setVisibility(View.GONE);
                } else {
                  mReinforceMethodTLayout.setVisibility(View.VISIBLE);
                }
              }
            });
        break;
      case R.id.et_project_re_method_t:
        final List<String> methodt = FormDataUtil.getProjectMethodt();
        PickViewUtil.showPickerViewOne(activity, "", methodt,
            new OptionsPickerView.OnOptionsSelectListener() {
              @Override
              public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String type = methodt.get(options1);
                mReinforceMethodT.setText(type);
                mReinforceMethodOther.setVisibility(
                    TextUtils.equals("其它", type) ? View.VISIBLE : View.GONE);
              }
            });
        break;
      case R.id.et_project_year:
        PickViewUtil.showTimePickerView(this, "年", true, new TimePickerView.OnTimeSelectListener() {
          @Override public void onTimeSelect(Date date, View v) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            mProjectYear.setText(String.valueOf(calendar.get(Calendar.YEAR)));
          }
        });
        break;
      case R.id.et_project_moth:
        PickViewUtil.showTimePickerView(this, "月", false,
            new TimePickerView.OnTimeSelectListener() {
              @Override public void onTimeSelect(Date date, View v) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                mProjectMoth.setText(String.valueOf(calendar.get(Calendar.MONTH) + 1));
              }
            });
        break;
      case R.id.et1_project_category:
        final List<String> yo = FormDataUtil.yesOrNo();
        PickViewUtil.showPickerViewOne(activity, "", yo,
            new OptionsPickerView.OnOptionsSelectListener() {
              @Override
              public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String type = yo.get(options1);
                mLifeEditText.setText(type);
              }
            });
        break;
      case R.id.et2_project_category:
        final List<String> pu = FormDataUtil.projectUse();
        PickViewUtil.showPickerViewOne(activity, "", pu,
            new OptionsPickerView.OnOptionsSelectListener() {
              @Override
              public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String type = pu.get(options1);
                mOrEditText.setText(type);
                mProjectTypeOther.setVisibility(
                    TextUtils.equals("其它", type) ? View.VISIBLE : View.GONE);
                mProjectTypeOther.setText("");
              }
            });
        break;
      default:
        break;
    }
  }

  private void initPicture(MyGridView gridView, int requestCode) {
    if (W == 0 || H == 0) {
      W = activity.getResources().getDisplayMetrics().widthPixels;
      H = activity.getResources().getDisplayMetrics().heightPixels;
    }

    ImageAdapter adapter = new ImageAdapter(this, W, requestCode);
    adapter.setListener(this);
    if (requestCode == 1001) {
      mBeforeAdapter = adapter;
    } else if (requestCode == 1002) {
      mAfterAdapter = adapter;
    } else if (requestCode == 1003) {
      mIngAdapter = adapter;
    }

    gridView.setAdapter(adapter);

    LinearLayout.LayoutParams lp =
        new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    gridView.setLayoutParams(lp);
    gridView.setPadding((int) (W * 0.09), Utils.dp2px(activity, 10), (int) (W * 0.09),
        Utils.dp2px(activity, 10));
    gridView.setHorizontalSpacing((int) (W * 0.01));
    gridView.setVerticalSpacing((int) (W * 0.01));
  }

  /**
   * 初始化view
   */
  private void initView() {

    initPicture(mBeforeGridView, 1001);
    initPicture(mAfterGridView, 1002);
    initPicture(mIngGridView, 1003);
  }

  /**
   * 初始化数据
   */
  private void initData() {
    Intent intent = getIntent();
    if (intent == null) {
      finish();
    }

    reinforceData = (ReinforceResult.ReinforceData) intent.getSerializableExtra("reinforce");
    if (reinforceData == null) {
      finish();
    }

    lng = reinforceData.longitude;
    lat = reinforceData.latitude;

    etLng.setText(lng);
    etLat.setText(lat);

    tvSave.setText("保存");
    tvClear.setText("清空");

    tvTitle.setText("房屋设施加固工程调查表");

    String status = reinforceData.status;
    if (TextUtils.equals("1", status) || TextUtils.equals("3", status)) {
      setEnable(mParentView);
    }

    setCommitView(status);

    if (!TextUtils.isEmpty(reinforceData.id)) {//id不为空表示为已上传的加固工程信息 获取保存资料
      getReinforceData();
    } else {
      getTianDiTuLocations(lng, lat, etBuildingAddress, etProvince, etCity, etArea);
    }

    updateLocation();
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {
      if (data == null) {
        return;
      }
      if (requestCode == 1001 || requestCode == 1002 || requestCode == 1003) {
        List<String> pathList = data.getStringArrayListExtra("result");
        List<String> pull = new ArrayList<>();
        List<ImageURL> imageURLS = new ArrayList<>();
        if (pathList == null || pathList.size() == 0) {
          return;
        }
        String toPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/";
        for (String path : pathList) {
          String newPath = path;
          //if (path != null && path.contains("com.buildings")) {
          //  newPath = Utils.savePictureBitmap(activity, path, toPath, true);
          //} else {
          //  newPath = Utils.savePictureBitmap(activity, path, toPath, false);
          //}
          ImageURL imageURL = new ImageURL();
          imageURL.setThumbnail(newPath);
          imageURLS.add(imageURL);
          pull.add(newPath);
        }

        switch (requestCode) {
          case 1001:
            mBeforeAdapter.update(imageURLS);
            break;
          case 1002:
            mAfterAdapter.update(imageURLS);
            break;
          case 1003:
            mIngAdapter.update(imageURLS);
            break;
        }
        //uploadImage(pull, requestCode);
      }
    }
  }

  private void uploadImage(List<String> images, final int requestCode, final int type) {

    if (images == null || images.size() == 0) {
      if (imageIndex.incrementAndGet() == 3) {
        commitToServer(type);
      }
      return;
    }

    UploadImage load = new UploadImage.Builder().context(this)
        .setBuildingCode(projectCode)
        .setImages(images)
        .build();

    load.upLoadImages(new Callback() {
      @Override public void onFailure(@NonNull Call call, @NonNull IOException e) {

        if (call == null && e == null) {
          if (imageIndex.incrementAndGet() == 3) {
            commitToServer(type);
          }
          return;
        }
        runOnUiThread(new Runnable() {
          @Override public void run() {
            CustomToast.showToast(activity, "图片上传失败");
          }
        });
      }

      @Override public void onResponse(@NonNull Call call, @NonNull Response response)
          throws IOException {

        if (!response.isSuccessful() || response.body() == null) {
          runOnUiThread(new Runnable() {
            @Override public void run() {
              CustomToast.showToast(activity, "图片上传失败");
            }
          });
          return;
        }

        final String result = response.body().string();
        Log.e("imageResult", result + "");
        if (response.body() != null) {
          response.body().close();
        }

        runOnUiThread(new Runnable() {
          @Override public void run() {

            ReinforceImageResult reinforceImageResult =
                new Gson().fromJson(result, ReinforceImageResult.class);
            if (reinforceImageResult == null) {
              CustomToast.showToast(activity, "图片上传失败");
              return;
            }
            int code = reinforceImageResult.code;
            if (code != 200) {
              CustomToast.showToast(activity, "图片上传失败");
              return;
            }

            if (requestCode == 1001) {
              mBeforeAdapter.setServerList(reinforceImageResult.data);
              reinforceData.pictureBeforeConstruction =
                  CheckUtils.formatImageList(mBeforeAdapter.getServerList());
            } else if (requestCode == 1002) {
              mAfterAdapter.setServerList(reinforceImageResult.data);
              reinforceData.pictureCompleteConstruction =
                  CheckUtils.formatImageList(mAfterAdapter.getServerList());
            } else if (requestCode == 1003) {
              mIngAdapter.setServerList(reinforceImageResult.data);
              reinforceData.pictureProcessConstruction =
                  CheckUtils.formatImageList(mIngAdapter.getServerList());
            }

            if (imageIndex.incrementAndGet() == 3) {
              commitToServer(type);
            }
          }
        });
      }
    });
  }

  @Override public void setProvinceText(String province) {
    super.setProvinceText(province);
    etProvince.setText(province);
  }

  @Override public void setCityText(String city) {
    super.setCityText(city);
    etCity.setText(city);
  }

  @Override public void setAreaText(String area) {
    super.setAreaText(area);
    etArea.setText(area);
  }

  @Override public void add(int requestCode, int size) {
    isPictureEdit = true;
    goImage(requestCode, size);
  }

  @Override public void delete(int position, ImageURL url) {
    isPictureEdit = true;
    Constant.imageList.remove(url.getThumbnail());
  }

  private void save(int type) {
    if (TextUtils.isEmpty(etNumber.getText().toString())) {
      //建筑物编号为空，不能保存操作
      CustomToast.showToast(activity, "没有工程编号，无法保存，请重新进入该界面");
      finish();
      return;
    }

    if (myDialog == null) {
      myDialog = DialogUtils.showRefreshDialog(activity);
      myDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
        @Override public void onDismiss(DialogInterface dialog) {
          tvSave.setEnabled(true);
          mCommitView.setEnabled(true);
        }
      });
    } else {
      myDialog.show();
    }
    tvSave.setEnabled(false);
    mCommitView.setEnabled(false);
    if (!isPictureEdit) {
      commitToServer(type);
    } else {
      if (TextUtils.isEmpty(projectCode)) {
        CustomToast.showToast(activity, "没有工程编号，无法保存，请重新进入该界面");
        finish();
        return;
      }
      imageIndex.set(0);
      uploadImage(mBeforeAdapter.getStringList(), 1001, type);
      uploadImage(mAfterAdapter.getStringList(), 1002, type);
      uploadImage(mIngAdapter.getStringList(), 1003, type);
    }
    updateLocation();//上传活动轨迹
  }

  private void commitToServer(int type) {
    if (type == 0) {
      saveReinforceData();
    }
    String id = reinforceData.id;
    if (!TextUtils.isEmpty(id)) {
      update(type);
    } else {
      saveOrCommit(type);
    }
  }

  private void saveReinforceData() {
    if (reinforceData == null) {
      reinforceData = new ReinforceResult.ReinforceData();
    }
    reinforceData.createUser = (String) SPUtil.get("userName", "");
    reinforceData.number = etNumber.getText().toString();
    reinforceData.longitude = etLng.getText().toString();
    reinforceData.latitude = etLat.getText().toString();
    reinforceData.province = etProvince.getText().toString();
    if (TextUtils.isEmpty(reinforceData.province)) {
      reinforceData.isSaveAll = "0";
    }
    reinforceData.city = etCity.getText().toString();
    if (TextUtils.isEmpty(reinforceData.city)) {
      reinforceData.isSaveAll = "0";
    }
    reinforceData.area = etArea.getText().toString();
    if (TextUtils.isEmpty(reinforceData.area)) {
      reinforceData.isSaveAll = "0";
    }
    reinforceData.address = etBuildingAddress.getText().toString();
    if (TextUtils.isEmpty(reinforceData.address)) {
      reinforceData.isSaveAll = "0";
    }
    reinforceData.name = mProjectName.getText().toString();
    if (TextUtils.isEmpty(reinforceData.name)) {
      reinforceData.isSaveAll = "0";
    }
    reinforceData.category = mProjectCategory.getText().toString();
    if (TextUtils.isEmpty(reinforceData.category)) {
      reinforceData.isSaveAll = "0";
    }
    if (TextUtils.equals("应急避难场所建设", mProjectCategory.getText().toString())) {
      reinforceData.shelterArea = mArrayText.getText().toString();
      if (TextUtils.isEmpty(reinforceData.shelterArea)) {
        reinforceData.isSaveAll = "0";
      }
      reinforceData.shelterGalleryful = mPeopleText.getText().toString();
      if (TextUtils.isEmpty(reinforceData.shelterGalleryful)) {
        reinforceData.isSaveAll = "0";
      }
      reinforceData.isShelterHaveLivingFacilities = mLifeEditText.getText().toString();
      if (TextUtils.isEmpty(reinforceData.isShelterHaveLivingFacilities)) {
        reinforceData.isSaveAll = "0";
      }

      reinforceData.shelterOriginalPurpose = mOrEditText.getText().toString();
      if (TextUtils.isEmpty(reinforceData.shelterOriginalPurpose)) {
        reinforceData.isSaveAll = "0";
      }

      if (TextUtils.equals("其它", reinforceData.shelterOriginalPurpose)) {
        reinforceData.shelterOriginalPurposeSupplement = mProjectTypeOther.getText().toString();
        if (TextUtils.isEmpty(reinforceData.shelterOriginalPurposeSupplement)) {
          reinforceData.isSaveAll = "0";
        }
      }
    }
    reinforceData.type = mProjectType.getText().toString();
    if (TextUtils.isEmpty(reinforceData.type)) {
      reinforceData.isSaveAll = "0";
    }
    if (TextUtils.equals("其它", reinforceData.type)) {
      reinforceData.typeSupplement = mProjectTypeOther.getText().toString();
      if (TextUtils.isEmpty(reinforceData.typeSupplement)) {
        reinforceData.isSaveAll = "0";
      }
    }
    reinforceData.measure = mReinforceMethod.getText().toString();
    if (TextUtils.isEmpty(reinforceData.measure)) {
      reinforceData.isSaveAll = "0";
    }
    reinforceData.measureSecond = mReinforceMethodT.getText().toString();
    if (TextUtils.isEmpty(reinforceData.measureSecond)) {
      reinforceData.isSaveAll = "0";
    }
    if (TextUtils.equals("其它", reinforceData.measureSecond)) {
      reinforceData.measureSupplement = mReinforceMethodOther.getText().toString();
      if (TextUtils.isEmpty(reinforceData.measureSupplement)) {
        reinforceData.isSaveAll = "0";
      }
    }
    String year = mProjectYear.getText().toString();
    String moth = mProjectMoth.getText().toString();
    if (!TextUtils.isEmpty(year) && !TextUtils.isEmpty(moth)) {
      reinforceData.reinforceTime =
          mProjectYear.getText().toString() + "-" + mProjectMoth.getText().toString();
    }
    if (TextUtils.isEmpty(reinforceData.reinforceTime)) {
      reinforceData.isSaveAll = "0";
    }

    reinforceData.pictureBeforeConstruction =
        CheckUtils.formatImageList(mBeforeAdapter.getServerList());
    if (TextUtils.isEmpty(reinforceData.pictureBeforeConstruction)) {
      reinforceData.isSaveAll = "0";
    }
    reinforceData.pictureProcessConstruction =
        CheckUtils.formatImageList(mIngAdapter.getServerList());
    if (TextUtils.isEmpty(reinforceData.pictureProcessConstruction)) {
      reinforceData.isSaveAll = "0";
    }
    reinforceData.pictureCompleteConstruction =
        CheckUtils.formatImageList(mAfterAdapter.getServerList());
    if (TextUtils.isEmpty(reinforceData.pictureCompleteConstruction)) {
      reinforceData.isSaveAll = "0";
    }

    if (TextUtils.isEmpty(reinforceData.isSaveAll)) {
      reinforceData.isSaveAll = "1";
    }
  }

  private boolean checkComplete() {

    if (reinforceData == null) {
      reinforceData = new ReinforceResult.ReinforceData();
    }

    if (!CheckUtils.checkNullEditText(etNumber, "请输入工程编号")) {
      return false;
    }
    reinforceData.number = etNumber.getText().toString();

    if (!CheckUtils.checkNullEditText(etLng, "请输入经度")) {
      return false;
    }
    reinforceData.longitude = etLng.getText().toString();

    if (!CheckUtils.checkNullEditText(etLat, "请输入纬度")) {
      return false;
    }
    reinforceData.latitude = etLat.getText().toString();

    if (!CheckUtils.checkNullEditText(etProvince, "请选择省")) {
      return false;
    }
    reinforceData.province = etProvince.getText().toString();

    if (!CheckUtils.checkNullEditText(etCity, "请选择市")) {
      return false;
    }
    reinforceData.city = etCity.getText().toString();
    if (!CheckUtils.checkNullEditText(etArea, "请选择区")) {
      return false;
    }
    reinforceData.area = etArea.getText().toString();
    if (!CheckUtils.checkNullEditText(etBuildingAddress, "请输入工程地址")) {
      return false;
    }
    reinforceData.address = etBuildingAddress.getText().toString();
    if (!CheckUtils.checkNullEditText(mProjectName, "请输入工程名称")) {
      return false;
    }
    reinforceData.name = mProjectName.getText().toString();
    if (!CheckUtils.checkNullEditText(mProjectCategory, "请输入工程类别")) {
      return false;
    }

    reinforceData.category = mProjectCategory.getText().toString();
    if (!CheckUtils.checkNullEditText(mProjectType, "请输入工程类型")) {
      return false;
    }
    reinforceData.type = mProjectType.getText().toString();

    if (TextUtils.equals("应急避难场所建设", mProjectCategory.getText().toString())) {
      if (!CheckUtils.checkNullEditText(mArrayText, "请输入场所面积")) {
        return false;
      }

      reinforceData.shelterArea = mArrayText.getText().toString();

      if (!CheckUtils.checkNullEditText(mPeopleText, "请输入可容纳人数")) {
        return false;
      }
      reinforceData.shelterGalleryful = mPeopleText.getText().toString();

      if (!CheckUtils.checkNullEditText(mLifeEditText, "请填写是否配备生活设施")) {
        return false;
      }

      reinforceData.isShelterHaveLivingFacilities = mLifeEditText.getText().toString();

      if (!CheckUtils.checkNullEditText(mPeopleText, "请填写原厂址用途")) {
        return false;
      }
      reinforceData.shelterOriginalPurpose = mOrEditText.getText().toString();

      if (TextUtils.equals("其它", reinforceData.shelterOriginalPurpose)) {
        if (!CheckUtils.checkNullEditText(mProjectTypeOther, "请输入原厂址用途其它补充")) {
          return false;
        }
        reinforceData.shelterOriginalPurposeSupplement = mProjectTypeOther.getText().toString();
      }
    }

    if (TextUtils.equals("其它", reinforceData.type)) {
      if (!checkNullEditText(mProjectTypeOther, "请输入工程类型其它补充说明")) {
        return false;
      }
      reinforceData.typeSupplement = mProjectTypeOther.getText().toString();
    }
    if (!CheckUtils.checkNullEditText(mReinforceMethod, "请输入加固方式")) {
      return false;
    }
    reinforceData.measure = mReinforceMethod.getText().toString();

    if (!CheckUtils.checkNullEditText(mReinforceMethodT, "请输入加固方式")) {
      return false;
    }
    reinforceData.measureSecond = mReinforceMethodT.getText().toString();

    if (TextUtils.equals("其它", reinforceData.measureSecond)) {
      if (!checkNullEditText(mReinforceMethodOther, "请输入加固措施其它补充说明")) {
        return false;
      }
      reinforceData.measureSupplement = mReinforceMethodOther.getText().toString();
    }
    if (!CheckUtils.checkNullEditText(mProjectYear, "请输入工程加固时间")) {
      return false;
    }
    if (!CheckUtils.checkNullEditText(mProjectMoth, "请输入工程加固时间")) {
      return false;
    }
    reinforceData.reinforceTime =
        mProjectYear.getText().toString() + "-" + mProjectMoth.getText().toString();

    if (mAfterAdapter != null) {
      List<ImageURL> list = mAfterAdapter.getUrlList();
      if (list == null || list.size() < 2) {
        CustomToast.showToast(this, "请选择竣工图片");
        return false;
      }

      reinforceData.pictureBeforeConstruction = formatImageList(mBeforeAdapter.getServerList());
      reinforceData.pictureProcessConstruction = formatImageList(mIngAdapter.getServerList());
      reinforceData.pictureCompleteConstruction = formatImageList(mAfterAdapter.getServerList());
    }

    reinforceData.createUser = (String) SPUtil.get("userName", "");

    reinforceData.isSaveAll = "1";
    return true;
  }

  private void setReinforceData(ReinforceResult.ReinforceData reinforceData) {
    if (reinforceData == null) {
      return;
    }

    if (!TextUtils.isEmpty(reinforceData.reason) && TextUtils.equals("2", reinforceData.status)) {
      tvReason.setVisibility(View.VISIBLE);
      tvReason.setText(reinforceData.reason);
    } else {
      tvReason.setVisibility(View.GONE);
    }

    CheckUtils.setText(reinforceData.number, etNumber);
    CheckUtils.setText(reinforceData.longitude, etLng);
    CheckUtils.setText(reinforceData.latitude, etLat);
    CheckUtils.setText(reinforceData.province, etProvince);
    CheckUtils.setText(reinforceData.city, etCity);
    CheckUtils.setText(reinforceData.area, etArea);
    CheckUtils.setText(reinforceData.address, etBuildingAddress);
    CheckUtils.setText(reinforceData.name, mProjectName);
    CheckUtils.setText(reinforceData.category, mProjectCategory);
    CheckUtils.setText(reinforceData.type, mProjectType);
    if ("应急避难场所建设".equals(reinforceData.category)) {
      mBuildingLayout.setVisibility(View.VISIBLE);
      CheckUtils.setText(reinforceData.shelterArea, mArrayText);
      CheckUtils.setText(reinforceData.shelterGalleryful, mPeopleText);
      CheckUtils.setText(reinforceData.isShelterHaveLivingFacilities, mLifeEditText);
      CheckUtils.setText(reinforceData.shelterOriginalPurpose, mOrEditText);
      mProjectTypeOther.setVisibility(
          TextUtils.equals("其它", reinforceData.shelterOriginalPurpose) ? View.VISIBLE : View.GONE);
      if (mProjectTypeOther.getVisibility()==View.VISIBLE){
        mProjectTypeOther.setText(reinforceData.shelterOriginalPurposeSupplement);
      }
    } else {
      mBuildingLayout.setVisibility(View.GONE);
      mProjectTypeOther.setVisibility(
          TextUtils.equals("其它", reinforceData.type) ? View.VISIBLE : View.GONE);
      CheckUtils.setText(reinforceData.typeSupplement, mProjectTypeOther);
    }

    CheckUtils.setText(reinforceData.typeSupplement, mProjectTypeOther);
    CheckUtils.setText(reinforceData.measure, mReinforceMethod);
    CheckUtils.setText(reinforceData.measureSecond, mReinforceMethodT);
    mReinforceMethodOther.setVisibility(
        TextUtils.equals("其它", reinforceData.measureSecond) ? View.VISIBLE : View.GONE);
    CheckUtils.setText(reinforceData.measureSupplement, mReinforceMethodOther);

    String re = reinforceData.reinforceTime;
    if (!TextUtils.isEmpty(re)) {
      String[] res = re.split("-");
      if (res.length == 2) {
        CheckUtils.setText(res[0], mProjectYear);
        CheckUtils.setText(res[1], mProjectMoth);
      }
    }
    List<String> before = CheckUtils.formatList(reinforceData.pictureBeforeConstruction);
    mBeforeAdapter.setData(before);

    List<String> ing = CheckUtils.formatList(reinforceData.pictureProcessConstruction);
    mIngAdapter.setData(ing);

    List<String> complete = CheckUtils.formatList(reinforceData.pictureCompleteConstruction);
    mAfterAdapter.setData(complete);
  }

  /**
   * 图片
   */
  public void goImage(int requestCode, int size) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
        && ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA)
        != PackageManager.PERMISSION_GRANTED) {
      //用户没有给与相机授权
      Utils.askMultiPermission(activity, new SelectPermissionCallBack() {
        @Override public void onGranted() {

        }
      }, Manifest.permission.CAMERA);
      return;
    }
    // 自定义图片加载器
    ISNav.getInstance().init(new ImageLoader() {
      @Override public void displayImage(Context context, String path, ImageView imageView) {
        Glide.with(context).load(path).into(imageView);
      }
    });

    ISListConfig config = new ISListConfig.Builder()
        // 是否多选
        .multiSelect(true)
        .btnText("确定")
        // 确定按钮背景色
        //.btnBgColor(Color.parseColor(""))
        // 确定按钮文字颜色
        .btnTextColor(Color.WHITE)
        // 使用沉浸式状态栏
        .statusBarColor(Color.parseColor("#5887F9"))
        .title("图片选择")
        .titleColor(Color.WHITE)
        .titleBgColor(Color.parseColor("#5887F9"))
        .allImagesText("All Images")
        .needCrop(false)
        .cropSize(1, 1, 200, 200)
        // 第一个是否显示相机
        .needCamera(true)
        // 最大选择图片数量
        .maxNum(5)
        .rememberSelected(true)
        .build();
    // 跳转到图片选择器

    List<ImageURL> list = new ArrayList<>();
    switch (requestCode) {
      case 1001:
        list = mBeforeAdapter.getUrlList();
        break;
      case 1002:
        list = mAfterAdapter.getUrlList();
        break;
      case 1003:
        list = mIngAdapter.getUrlList();
        break;
    }

    if (list != null && list.size() > 0) {
      Constant.imageList.clear();
      for (ImageURL url : list) {
        if (!TextUtils.isEmpty(url.getThumbnail())) {
          Constant.imageList.add(url.getThumbnail());
        }
      }
    }

    ISNav.getInstance().toListActivity(this, config, requestCode);
  }

  private void saveOrCommit(int type) {
    String host = Api.REINFORCE + "save/0/" + type;

    if (reinforceData == null) {
      return;
    }

    if (type == 1) {
      if (TextUtils.isEmpty(reinforceData.pictureCompleteConstruction)) {
        CustomToast.showToast(this, "请选择竣工图片");
        if (myDialog != null) {
          myDialog.dismiss();
        }
        return;
      }
    }
    Gson gson = new Gson();
    String json = gson.toJson(reinforceData);

    MyHttpClient.newBuilder()
        .post()
        .url(host)
        .addParam(json)
        .build()
        .enqueue(new BaseCallBack<LoginBean>() {
          @Override public void onSuccess(LoginBean bean) {
            super.onSuccess(bean);
            if (bean.getCode() == 200) {
              CustomToast.showToast(activity, "保存成功");
              setResult(RESULT_OK);
              finish();
            }
            if (myDialog != null) {
              myDialog.dismiss();
            }
          }

          @Override public void onFailure(Call call, IOException e) {
            super.onFailure(call, e);
            if (myDialog != null) {
              myDialog.dismiss();
            }
            CustomToast.showToast(activity, "网络异常");
          }

          @Override public void onError(int code) {
            super.onError(code);
            if (myDialog != null) {
              myDialog.dismiss();
            }
            CustomToast.showToast(activity, "网络异常");
          }
        });
  }

  /**
   * 获取加固工程编号
   */
  private void getProjectCode() {
    String host = Api.REINFORCE + "projectCode";

    MyHttpClient.newBuilder().get().url(host).build().enqueue(new BaseCallBack<BuildingCodeBean>() {
      @Override public void onSuccess(BuildingCodeBean resultBean) {
        super.onSuccess(resultBean);
        if (resultBean.getCode() == 200 && resultBean.getData() != null) {
          projectCode = resultBean.getData();
          etNumber.setText(resultBean.getData());
          setDefaultView();
        } else {
          CustomToast.showToast(activity, "获取建筑物编号失败");
        }
      }

      @Override public void onFailure(Call call, IOException e) {
        super.onFailure(call, e);
        CustomToast.showToast(activity, "获取建筑物编号失败");
      }

      @Override public void onError(int code) {
        super.onError(code);
        CustomToast.showToast(activity, "获取建筑物编号失败");
      }
    });
  }

  private void getReinforceData() {

    if (reinforceData == null) {
      return;
    }
    String id = reinforceData.id;
    if (TextUtils.isEmpty(id)) {
      return;
    }

    String host = Api.REINFORCE + "getone/" + id;

    MyHttpClient.newBuilder().get().url(host).build().enqueue(new BaseCallBack<ReinforceResult>() {
      @Override public void onSuccess(ReinforceResult resultBean) {
        super.onSuccess(resultBean);
        if (resultBean.getCode() == 200 && resultBean.data != null) {
          reinforceData = resultBean.data;
          projectCode = reinforceData.number;
          setReinforceData(resultBean.data);
        } else {
          CustomToast.showToast(activity, "获取建筑物编号失败");
        }
      }

      @Override public void onFailure(Call call, IOException e) {
        super.onFailure(call, e);
        CustomToast.showToast(activity, "获取建筑物编号失败");
      }

      @Override public void onError(int code) {
        super.onError(code);
        CustomToast.showToast(activity, "获取建筑物编号失败");
      }
    });
  }

  private void update(int type) {

    if (reinforceData == null) {
      return;
    }

    if (type == 1) {
      if (TextUtils.isEmpty(reinforceData.pictureCompleteConstruction)) {
        CustomToast.showToast(this, "请选择竣工图片");
        if (myDialog != null) {
          myDialog.dismiss();
        }
        return;
      }
    }
    String host = Api.REINFORCE + "update/" + type;

    Gson gson = new Gson();
    String json = gson.toJson(reinforceData);

    MyHttpClient.newBuilder()
        .post()
        .url(host)
        .addParam(json)
        .build()
        .enqueue(new BaseCallBack<LoginBean>() {
          @Override public void onSuccess(final LoginBean bean) {
            super.onSuccess(bean);
            runOnUiThread(new Runnable() {
              @Override public void run() {
                if (bean.getCode() == 200) {
                  CustomToast.showToast(activity, "保存成功");
                  setResult(RESULT_OK);
                  finish();
                }
                if (myDialog != null) {
                  myDialog.dismiss();
                }
              }
            });
          }

          @Override public void onFailure(Call call, IOException e) {
            super.onFailure(call, e);
            runOnUiThread(new Runnable() {
              @Override public void run() {
                if (myDialog != null) {
                  myDialog.dismiss();
                }
                CustomToast.showToast(activity, "网络异常");
              }
            });
          }

          @Override public void onError(int code) {
            super.onError(code);
            if (myDialog != null) {
              myDialog.dismiss();
            }
            CustomToast.showToast(activity, "网络异常");
          }
        });
  }

  /**
   * 设置不可点击
   */
  private void setEnable(View rootView) {
    if (rootView == null) {
      return;
    }
    if (rootView instanceof ViewGroup) {
      ViewGroup viewGroup = (ViewGroup) rootView;
      int childCount = viewGroup.getChildCount();
      for (int i = 0; i < childCount; i++) {
        View view = viewGroup.getChildAt(i);
        if (view instanceof ViewGroup) {
          setEnable(view);
        } else {
          view.setEnabled(false);
        }
      }
    }
  }

  public void getTianDiTuLocations(String lng, String lat,

      final EditText etBuildingAddress, final EditText etProvince, final EditText etCity,
      final EditText etArea) {

    String url = "http://api.tianditu.gov.cn/geocoder?postStr={'lon':"
        + lng
        + ",'lat':"
        + lat
        + ",'ver':1}&type=geocode&tk="
        + com.buildings.api.Constant.TIAN_DI_TU_ANDROID_KEY;
    //        String url = "http://api.tianditu.gov.cn/geocoder?postStr={%27lon%27:116.28,%27lat%27:40.1419,%27ver%27:1}&type=geocode&tk=3bd24441a20ee975f046a8d7417b936a";
    final JsonBuilder jsonBuilder = new JsonBuilder(this);
    //        jsonBuilder.put("doctorMobile", etPhone.getText().toString());

    MyHttpClient.newBuilder().get().url(url)
        //                .addParam(jsonBuilder.toJsonString())
        .build().enqueue(new BaseCallBack<String>() {
      @Override public void onSuccess(String response) {
        super.onSuccess(response);
        try {
          JSONObject jsonObject = new JSONObject(response);
          if (TextUtils.equals(jsonObject.getString("msg"), "ok")) {
            JSONObject object =
                jsonObject.getJSONObject("result").getJSONObject("addressComponent");
            String formatted_address =
                jsonObject.getJSONObject("result").getString("formatted_address");//建筑地址
            String province = object.getString("province");//省
            String city = object.getString("city");//市
            String county = object.getString("county");//区
            String poi = object.getString("poi");//建筑名称
            String county_code = object.getString("county_code");//区编码

            if (!TextUtils.isEmpty(formatted_address)) {
              etBuildingAddress.setText(formatted_address);
            }
            if (!TextUtils.isEmpty(province)) {
              etProvince.setText(province);
              etCity.setText(city);
              etArea.setText(county);
            }
            getProjectCode();
          }
        } catch (JSONException e) {
          e.printStackTrace();
        }
      }

      @Override public void onFailure(Call call, IOException e) {
        super.onFailure(call, e);
      }

      @Override public void onError(int code) {
        super.onError(code);
      }
    });
  }

  public void setDefaultView() {
    mProjectCategory.setText("城镇住宅");
    mProjectType.setText("砖混结构");
    mReinforceMethod.setText("工程加固位置");
    mReinforceMethodT.setText("主体结构");
    Calendar calendar = Calendar.getInstance();
    mProjectYear.setText(String.valueOf(calendar.get(Calendar.YEAR)));
    mProjectMoth.setText(String.valueOf(calendar.get(Calendar.MONTH) + 1));
  }

  private void setCommitView(String status) {
    if (TextUtils.equals("0", status) || TextUtils.equals("2", status)) {
      tvClear.setVisibility(View.VISIBLE);
      tvSave.setVisibility(View.VISIBLE);
      mCommitView.setVisibility(View.VISIBLE);
      mAfterAdapter.setEdit(true);
      mBeforeAdapter.setEdit(true);
      mIngAdapter.setEdit(true);
    } else {
      tvClear.setVisibility(View.GONE);
      tvSave.setVisibility(View.GONE);
      mCommitView.setVisibility(View.GONE);
      mAfterAdapter.setEdit(false);
      mBeforeAdapter.setEdit(false);
      mIngAdapter.setEdit(false);
    }
  }
}
